import { createRouter,createWebHashHistory } from "vue-router"
import { CONFIG } from "../config/index.js"
import { userRouters } from "./user.js"
import { clusterRouters } from "./cluster.js"
import { nodeRouters } from "./node.js"
import { namespaceRouters } from "./namespace.js"

const Login = () => import('../view/Login.vue')
// const Index = () => import('../view/Index.vue')
const Layout = () => import('../view/layout/Layout.vue')

const routes = [
    userRouters,
    clusterRouters,
    nodeRouters,
    namespaceRouters,
    {
        path: "/login",
        component: Login,
    },
    {
        path: "/",
        component: Layout,
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes,
})

//路由前置守卫
router.beforeEach(
    (to,from,next) => {
        //1.访问的是login,本地没有存储token,不处理  ==> next()
        //2.访问的是login,本地存储了token,跳转到根目录  ==> next("/")
        //3.访问的不是login,本地存储了token,不处理  ==> next()
        //4.访问的不是login,本地没有存储token,跳转到登录页面 ==> next("login")
        //拿到访问路径
        const toPath =to.path
        //判断请求链接带不带/login,找到关键字值为0，没找到值为-1
        const toLogin = toPath.indexOf("/login")
        //判断本地是否有token
        const tokenStatus = window.localStorage.getItem(CONFIG.TOKEN_NAME)
        if (toLogin == 0 && tokenStatus){
            next("/")
        }else if (toLogin == 0 && !tokenStatus){
            next()
        }else if (tokenStatus){
            next()
        }else{
            next("/login")
        }
    }
)
export default router